package com.haiqiu.busines.service.impl;

import com.haiqiu.busines.entity.SysEmail;
import com.haiqiu.busines.mapper.EmailMapper;
import com.haiqiu.busines.service.SysEmailService;
import com.haiqiu.common.mail.MailService;
import com.haiqiu.common.exception.BaseException;
import com.haiqiu.common.page.PageRequest;
import com.haiqiu.common.page.PageResponse;
import com.haiqiu.common.result.Constants;
import com.haiqiu.common.utils.tools.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author: HaiQiu
 * @Date: 2021/4/6
 * @Description: 公告逻辑层
 */
@Service
public class SysEmailServiceImpl implements SysEmailService {

    @Autowired
    private EmailMapper emailMapper;

    @Autowired
    private MailService mailService;


    /**
     * 根据ID删除数据
     *
     * @param id 数据ID
     */
    @Override
    public void deleteByPrimaryKey(Long id) {
        if (StringUtils.isEmpty(id)) {
            throw new BaseException(Constants.ID_EXITS);
        }
        if (emailMapper.deleteByPrimaryKey(id) == 0) {
            throw new BaseException(Constants.FAIL_DEL);
        }
    }


    @Override
    public void insert(SysEmail sysEmailData) {
        SysEmail sysEmail = checkAddData(sysEmailData);
        Date date = new Date();
        sysEmail.setCreateTime(date);
        sysEmail.setUpdateTime(date);
        //判断是否发送邮件
        isSendEmail(sysEmail);

        if (emailMapper.insert(sysEmail) == 0) {
            throw new BaseException(Constants.FAIL_ADD);
        }
    }

    /**
     * 判断是否发送邮件
     * @param sysEmail 邮件实体
     */
    private void isSendEmail(SysEmail sysEmail) {
        //是否发送邮件
        if ( sysEmail.getStatus()!=null && sysEmail.getStatus().equals(Constants.EMAIL_PREPARE)) {
            try {
                //发送邮件类型
                if (!StringUtils.isEmpty(sysEmail.getSendType())){
                    if ("text".equals(sysEmail.getSendType())){
                        mailService.sendSimpleTextMailActual(sysEmail.getSubject(), sysEmail.getContent(),
                                sysEmail.getToWho().contains(",") ? sysEmail.getToWho().split(",") :  new String[]{sysEmail.getToWho()},
                                null,
                                null,
                                null);
                    }else {
                        mailService.sendHtmlMail(sysEmail.getSubject(), sysEmail.getContent(),
                                sysEmail.getToWho().contains(",") ? sysEmail.getToWho().split(",") :  new String[]{sysEmail.getToWho()});
                    }
                    sysEmail.setStatus(Constants.EMAIL_SEND);
                }else {
                    throw new BaseException("发送邮件类型不正确");
                }
            } catch (Exception e) {
                sysEmail.setStatus(Constants.EMAIL_FAIL);
            }
        } else {
            sysEmail.setStatus(Constants.EMAIL_DRAFT);
        }
    }

    /**
     * 检查数据
     *
     * @param sysEmail 公告实体
     * @return 返回检验后的实体
     */
    private SysEmail checkAddData(SysEmail sysEmail) {
        if (StringUtils.isEmpty(sysEmail)) {
            throw new BaseException("无效数据");
        }
        if (StringUtils.isEmpty(sysEmail.getContent())) {
            throw new BaseException("无效内容");
        }
        if (StringUtils.isEmpty(sysEmail.getSubject())) {
            throw new BaseException("无效主题");
        }
        if (StringUtils.isEmpty(sysEmail.getToWho())) {
            throw new BaseException("无效收件人");
        }
        if (StringUtils.isEmpty(sysEmail.getSendType())) {
            throw new BaseException("无效邮件类型");
        }
        return sysEmail;
    }


    /**
     * 根据ID查询
     *
     * @param id 数据ID
     * @return 公告实体
     */
    @Override
    public SysEmail selectByPrimaryKey(Long id) {
        SysEmail sysEmail = emailMapper.selectByPrimaryKey(id);
        if (sysEmail == null) {
            throw new BaseException(Constants.DATA_EXIT);
        }
        return sysEmail;
    }


    @Override
    public void updateByPrimaryKeySelective(SysEmail sysEmail) {
        //检查数据
        SysEmail checkDataSysEmail = checkAddData(sysEmail);
        checkDataSysEmail.setUpdateTime(new Date());
        //判断是否发送邮件
        isSendEmail(sysEmail);
        if (emailMapper.updateByPrimaryKeySelective(checkDataSysEmail) == 0) {
            throw new BaseException(Constants.FAIL_UPDATE);
        }
    }


    /**
     * 批量删除公告
     *
     * @param ids 数据ID集合
     * @return 成功条数
     */
    @Override
    public int delBatch(Set<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new BaseException(Constants.ID_EXITS);
        }
        int i = emailMapper.batchDel(ids);
        if (i == 0) {
            throw new BaseException(Constants.FAIL_DEL);
        }
        return i;
    }


    /**
     * 分页模糊查询
     *
     * @param request 查询实体（包含分页）
     * @return 返回分页数据
     */
    @Override
    public PageResponse<SysEmail> list(PageRequest<SysEmail> request) {
        SysEmail sysEmail = StringUtil.checkObjFieldIsNull(request.getParams());
        long count = emailMapper.count(sysEmail);
        PageResponse<SysEmail> response = new PageResponse<>();
        response.setPageSize(request.getPageSize());
        response.setTotal(count);
        response.setPageIndex(request.getPageIndex());
        if (count > 0) {
            List<SysEmail> list = emailMapper.page(sysEmail, request.getOffset(), request.getPageSize());
            response.setData(list);
        }
        return response;
    }


    @Override
    public List<SysEmail> all() {
        return emailMapper.all();
    }


}
